package cn.tx.erp.sys.controller;

import cn.tx.erp.sys.domain.Dept;
import cn.tx.erp.sys.domain.Role;
import cn.tx.erp.sys.domain.User;
import cn.tx.erp.sys.service.DeptService;
import cn.tx.erp.sys.service.RoleService;
import cn.tx.erp.sys.service.UserService;
import cn.tx.erp.sys.utils.Constast;
import cn.tx.erp.sys.utils.DataGridView;
import cn.tx.erp.sys.utils.ResultObj;
import cn.tx.erp.sys.vo.UserVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.junit.platform.commons.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户管理
 * @author Mxb
 * @version 1.0
 * @date 2020/7/11 18:30
 */
@RequestMapping("user")
@RestController
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private DeptService deptService;


    /**
     * 加载所有的用户信息
     * @param userVo
     * @return
     */
    @RequestMapping(value = "/loadAllUser", method = RequestMethod.GET)
    public DataGridView loadAllUser(UserVo userVo) {
        // mybatis plus 分页查询
        IPage<User> page = new Page<>(userVo.getPage(), userVo.getLimit());

        QueryWrapper<User> qw = new QueryWrapper<>();
        // 模糊查询
        //qw.like(StringUtils.isNotBlank(userVo.getName()), "loginname", userVo.getName());
        //qw.like(StringUtils.isNotBlank(userVo.getRemark()), "remark", userVo.getRemark());

        //qw.eq("type", Constast.USER_TYPE_NORMAL);  // 查询系统用户
        if (userVo.getDeptid() != null) {
            qw.eq(userVo.getName() != null, "deptid", userVo.getDeptid());
        }
        qw.eq(StringUtils.isNotBlank(userVo.getName()), "name", userVo.getName());
        qw.eq(StringUtils.isNotBlank(userVo.getAddress()), "address", userVo.getAddress());
        // 查询是否可用
        qw.eq(userVo.getAvailable() != null, "available", userVo.getAvailable());

        //qw.orderByDesc("createtime");
        // 分页使用page 不分页使用list
        this.userService.page(page, qw);

        //翻译内容 部门id 和部门领导
        List<User> records = page.getRecords();
        for (User user : records) {
            Integer deptid = user.getDeptid();
            Dept dept = deptService.getById(deptid);
            user.setDeptname(dept.getTitle());
        }
        System.out.println();
        return new DataGridView(0, "成功", page.getTotal(), records);
    }

    /**
     * 添加用户
     * @param userVo
     * @return
     */
    @RequestMapping(value = "/addUser")
    public ResultObj addUser(UserVo userVo) {
        try {
            // 设置时间
            userVo.setHiredate(new Date());
            this.userService.save(userVo);
            return ResultObj.ADD_SUCCESS;
        } catch (Exception e) {
            return ResultObj.ADD_ERR;
        }
    }

    /**
     * 更新用户
     * @param userVo
     * @return
     */
    @RequestMapping(value = "/updateUser")
    public ResultObj updateRole(UserVo userVo) {
        try {
            this.userService.updateById(userVo);
            return ResultObj.UPDATE_SUCCESS;
        } catch (Exception e) {
            return ResultObj.UPDATE_ERR;
        }
    }


    /**
     * 删除用户
     * @param userVo
     * @return
     */
    @RequestMapping(value = "/deleteUser")
    public ResultObj deleteRole(UserVo userVo) {
        try {
            this.userService.removeById(userVo.getId());
            return ResultObj.DELETE_SUCCESS;
        } catch (Exception e) {
            return ResultObj.DELETE_ERR;
        }
    }

    /**
     * 加载最大的排序码
     * @return
     */
    @RequestMapping("loadUserMaxOrderNum")
    public Map<String, Object> loadUserMaxOrderNum() {
        Map<String, Object> map = new HashMap<String, Object>();

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("ordernum");
        IPage<User> page = new Page<>(1, 1);
        List<User> list = this.userService.page(page, queryWrapper).getRecords();
        if (list.size() > 0) {
            map.put("value", list.get(0).getOrdernum() + 1);
        } else {
            map.put("value", 1);
        }
        return map;
    }

    /**
     * 根据id查询用户
     * @param id
     * @return
     */
    @RequestMapping("loadUserById")
    public DataGridView loadUserById(Integer id) {
        return new DataGridView(this.userService.getById(id));
    }

    /**
     * 根据用户ID查询角色并选中已拥有的角色
     */
    @RequestMapping("initRoleByUserId")
    public DataGridView initRoleByUserId(Integer id) {
        //1,查询所有可用的角色
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("available", Constast.AVAILABLE_TRUE);
        List<Map<String, Object>> listMaps = this.roleService.listMaps(queryWrapper);

        //2,查询当前用户拥有的角色ID集合
        List<Integer> currentUserRoleIds = this.roleService.queryUserRoleIdsByUid(id);
        for (Map<String, Object> map : listMaps) {
            Boolean LAY_CHECKED = false;
            Integer roleId = (Integer) map.get("id");
            for (Integer rid : currentUserRoleIds) {
                if (rid == roleId) {
                    LAY_CHECKED = true;
                    break;
                }
            }
            map.put("LAY_CHECKED", LAY_CHECKED);
        }
        return new DataGridView(Long.valueOf(listMaps.size()), listMaps);
    }

    /**
     * 保存用户和角色的关系
     */
    @RequestMapping("saveUserRole")
    public ResultObj saveUserRole(Integer uid, Integer[] ids) {
        try {
            this.userService.saveUserRole(uid, ids);
            return ResultObj.DIS_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DIS_ERR;
        }

    }


}
